from PySide2.QtWidgets import QApplication, QMessageBox
from PySide2.QtUiTools import QUiLoader

import socket
import time
import numpy as np
import subprocess
import threading

L = 0
angle = 0
result_flag = False

def get_result_thread():
    global L, angle, result_flag
    HOST = '127.0.0.1'
    PORT = 8000
    ADDRESS = (HOST, PORT)
    # 创建一个套接字
    tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定本地ip
    tcpServer.bind(ADDRESS)
    # 开始监听
    tcpServer.listen(5)

    while True:
        print("wait for connecting......")
        client_socket, client_address = tcpServer.accept()
        print("succeed connedted!")

        while True:
            data = client_socket.recv(1024)
            if data:
                client_socket.send(b"ok")
                print(data.decode())
                datas = data.decode().split(" ")
                L = float(datas[0])
                angle = float(datas[1])
                result_flag = True
                break
            else:
               print("Disconnected!")
               break

t0 = threading.Thread(target=get_result_thread)
t0.start()


def server_thread():
    global L, angle, result_flag
    p = subprocess.Popen("python3 /home/pi/workspace/stereo-cv/scripts/server/server.py",\
                         shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in iter(p.stdout.readline, b''):
        # print(line.decode())
        pass

    p.stdout.close()
    p.wait()

t = threading.Thread(target=server_thread)
t.start()

def send_cmd(cmd, address):
    ## 发送指令给机器人
    tcpClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建一个套接字
    tcpClient.connect(address) # 连接机器人

    tcpClient.send(cmd) # 发送指令
    data = tcpClient.recv(1024) #接收反馈值
    if data.decode() == b"ok":
        pass
    tcpClient.close() # 关闭连接

ip_filename = "/home/pi/workspace/stereo-cv/config/ip.txt"
ipA = ""
ipB = ""
with open(ip_filename, "r") as f:  # 打开文件
    data = f.readline()  # 读取文件
    data = f.readline()  # 读取文件
    datas = data.split(" ")
    ipA = datas[1].split("\n")[0]
    data = f.readline()  # 读取文件
    datas = data.split(" ")
    ipB = datas[1].split("\n")[0]
    f.close()
addressA = (ipA, 8000)
addressB = (ipB, 8000)

class Stats:

    def __init__(self):
        # 从文件中加载UI定义

        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load("/home/pi/workspace/stereo-cv/ui/edc.ui")

        self.ui.pushButton.clicked.connect(self.handleCalc)

    def handleCalc(self):
        global L, angle, result_flag

        send_cmd(b'detect_laser', addressA)
        send_cmd(b'detect_laser', addressB)
    
        print("start!")
        
        self.ui.textBrowser.setText("unknown")
        self.ui.textBrowser_2.setText("unknown")

        while True:
            if(result_flag):
                self.ui.textBrowser.setText('%.3f' % L + "m")
                self.ui.textBrowser_2.setText('%.3f' % angle + '°')
                result_flag = False
                break

def showUI():
    app = QApplication([])
    stats = Stats()
    stats.ui.show()
    app.exec_()
t_ui = threading.Thread(target=showUI)
t_ui.start()

while True:
    pass